import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'

// 窗口尺寸断点
export const BREAKPOINTS = {
  xs: 0,
  sm: 768,
  md: 1024,
  lg: 1280,
  xl: 1536,
  xxl: 1920
} as const

export type Breakpoint = keyof typeof BREAKPOINTS

// 布局配置
export interface LayoutConfig {
  sidebarWidth: number
  sidebarCollapsed: boolean
  chatAreaWidth: number
  taskPanelWidth: number
  rightPanelVisible: boolean
  bottomPanelHeight: number
  bottomPanelVisible: boolean
}

// 窗口状态
export interface WindowState {
  width: number
  height: number
  isFullscreen: boolean
  isFocused: boolean
  breakpoint: Breakpoint
  isOnline: boolean
}

// 面板配置
export interface PanelConfig {
  id: string
  title: string
  component: string
  visible: boolean
  width?: number
  height?: number
  minWidth?: number
  minHeight?: number
  maxWidth?: number
  maxHeight?: number
  resizable?: boolean
  position?: 'left' | 'right' | 'top' | 'bottom' | 'center'
}

// 窗口管理器
class WindowManager {
  private state = ref<WindowState>({
    width: window.innerWidth,
    height: window.innerHeight,
    isFullscreen: false,
    isFocused: document.hasFocus(),
    breakpoint: 'md' as Breakpoint,
    isOnline: navigator.onLine
  })

  private layout = ref<LayoutConfig>({
    sidebarWidth: 280,
    sidebarCollapsed: false,
    chatAreaWidth: 0, // 自动计算
    taskPanelWidth: 320,
    rightPanelVisible: true,
    bottomPanelHeight: 200,
    bottomPanelVisible: false
  })

  private panels = ref<Map<string, PanelConfig>>(new Map())
  private listeners: Array<() => void> = []

  constructor() {
    this.updateBreakpoint()
    this.addEventListeners()
  }

  // Getters
  get windowState() {
    return this.state
  }

  get layoutConfig() {
    return this.layout
  }

  get allPanels() {
    return this.panels
  }

  // 计算当前断点
  updateBreakpoint(): void {
    const width = this.state.value.width
    let breakpoint: Breakpoint = 'xs'

    for (const [key, value] of Object.entries(BREAKPOINTS)) {
      if (width >= value) {
        breakpoint = key as Breakpoint
      }
    }

    this.state.value.breakpoint = breakpoint
  }

  // 事件监听
  addEventListeners(): void {
    const handleResize = () => {
      this.state.value.width = window.innerWidth
      this.state.value.height = window.innerHeight
      this.updateBreakpoint()
      this.adjustLayoutForBreakpoint()
    }

    const handleFocus = () => {
      this.state.value.isFocused = true
    }

    const handleBlur = () => {
      this.state.value.isFocused = false
    }

    const handleFullscreenChange = () => {
      this.state.value.isFullscreen = !!document.fullscreenElement
    }

    const handleOnline = () => {
      this.state.value.isOnline = true
    }

    const handleOffline = () => {
      this.state.value.isOnline = false
    }

    window.addEventListener('resize', handleResize)
    window.addEventListener('focus', handleFocus)
    window.addEventListener('blur', handleBlur)
    document.addEventListener('fullscreenchange', handleFullscreenChange)
    window.addEventListener('online', handleOnline)
    window.addEventListener('offline', handleOffline)

    this.listeners.push(
      () => window.removeEventListener('resize', handleResize),
      () => window.removeEventListener('focus', handleFocus),
      () => window.removeEventListener('blur', handleBlur),
      () => document.removeEventListener('fullscreenchange', handleFullscreenChange),
      () => window.removeEventListener('online', handleOnline),
      () => window.removeEventListener('offline', handleOffline)
    )
  }

  // 移除事件监听
  removeEventListeners(): void {
    this.listeners.forEach(cleanup => cleanup())
    this.listeners = []
  }

  // 根据断点调整布局
  adjustLayoutForBreakpoint(): void {
    const breakpoint = this.state.value.breakpoint

    switch (breakpoint) {
      case 'xs':
      case 'sm':
        // 小屏幕：折叠侧边栏，隐藏右侧面板
        this.layout.value.sidebarCollapsed = true
        this.layout.value.rightPanelVisible = false
        this.layout.value.bottomPanelVisible = false
        break
      case 'md':
        // 中等屏幕：显示侧边栏，隐藏右侧面板
        this.layout.value.sidebarCollapsed = false
        this.layout.value.rightPanelVisible = false
        break
      case 'lg':
      case 'xl':
      case 'xxl':
        // 大屏幕：显示所有面板
        this.layout.value.sidebarCollapsed = false
        this.layout.value.rightPanelVisible = true
        break
    }
  }

  // 布局控制
  toggleSidebar(): void {
    this.layout.value.sidebarCollapsed = !this.layout.value.sidebarCollapsed
  }

  setSidebarWidth(width: number): void {
    this.layout.value.sidebarWidth = Math.max(200, Math.min(400, width))
  }

  toggleRightPanel(): void {
    this.layout.value.rightPanelVisible = !this.layout.value.rightPanelVisible
  }

  setTaskPanelWidth(width: number): void {
    this.layout.value.taskPanelWidth = Math.max(280, Math.min(500, width))
  }

  toggleBottomPanel(): void {
    this.layout.value.bottomPanelVisible = !this.layout.value.bottomPanelVisible
  }

  setBottomPanelHeight(height: number): void {
    this.layout.value.bottomPanelHeight = Math.max(150, Math.min(400, height))
  }

  // 全屏控制
  async toggleFullscreen(): Promise<void> {
    try {
      if (document.fullscreenElement) {
        await document.exitFullscreen()
      } else {
        await document.documentElement.requestFullscreen()
      }
    } catch (error) {
      console.error('Fullscreen toggle failed:', error)
    }
  }

  // 面板管理
  registerPanel(panel: PanelConfig): void {
    this.panels.value.set(panel.id, panel)
  }

  unregisterPanel(panelId: string): void {
    this.panels.value.delete(panelId)
  }

  showPanel(panelId: string): void {
    const panel = this.panels.value.get(panelId)
    if (panel) {
      panel.visible = true
    }
  }

  hidePanel(panelId: string): void {
    const panel = this.panels.value.get(panelId)
    if (panel) {
      panel.visible = false
    }
  }

  togglePanel(panelId: string): void {
    const panel = this.panels.value.get(panelId)
    if (panel) {
      panel.visible = !panel.visible
    }
  }

  // 布局预设
  applyLayout(layoutName: 'default' | 'compact' | 'focus' | 'presentation'): void {
    switch (layoutName) {
      case 'default':
        this.layout.value = {
          sidebarWidth: 280,
          sidebarCollapsed: false,
          chatAreaWidth: 0,
          taskPanelWidth: 320,
          rightPanelVisible: true,
          bottomPanelHeight: 200,
          bottomPanelVisible: false
        }
        break
      case 'compact':
        this.layout.value = {
          sidebarWidth: 240,
          sidebarCollapsed: false,
          chatAreaWidth: 0,
          taskPanelWidth: 280,
          rightPanelVisible: true,
          bottomPanelHeight: 150,
          bottomPanelVisible: false
        }
        break
      case 'focus':
        this.layout.value = {
          sidebarWidth: 280,
          sidebarCollapsed: true,
          chatAreaWidth: 0,
          taskPanelWidth: 320,
          rightPanelVisible: false,
          bottomPanelHeight: 200,
          bottomPanelVisible: false
        }
        break
      case 'presentation':
        this.layout.value = {
          sidebarWidth: 280,
          sidebarCollapsed: true,
          chatAreaWidth: 0,
          taskPanelWidth: 320,
          rightPanelVisible: false,
          bottomPanelHeight: 200,
          bottomPanelVisible: true
        }
        break
    }
  }

  // 保存和恢复布局
  saveLayoutToStorage(): void {
    const layoutData = {
      layout: this.layout.value,
      panels: Object.fromEntries(this.panels.value)
    }
    localStorage.setItem('window-layout', JSON.stringify(layoutData))
  }

  loadLayoutFromStorage(): void {
    try {
      const saved = localStorage.getItem('window-layout')
      if (saved) {
        const layoutData = JSON.parse(saved)
        if (layoutData.layout) {
          this.layout.value = { ...this.layout.value, ...layoutData.layout }
        }
        if (layoutData.panels) {
          Object.entries(layoutData.panels).forEach(([id, config]) => {
            this.panels.value.set(id, config as PanelConfig)
          })
        }
      }
    } catch (error) {
      console.error('Failed to load layout from storage:', error)
    }
  }

  // 清理
  destroy(): void {
    this.removeEventListeners()
  }
}

// 全局窗口管理器实例
const globalWindowManager = new WindowManager()

// 组合式API
export const useWindowManager = () => {
  const windowState = computed(() => globalWindowManager.windowState.value)
  const layoutConfig = computed(() => globalWindowManager.layoutConfig.value)
  const isSmallScreen = computed(() => 
    ['xs', 'sm'].includes(windowState.value.breakpoint)
  )
  const isMediumScreen = computed(() => 
    windowState.value.breakpoint === 'md'
  )
  const isLargeScreen = computed(() => 
    ['lg', 'xl', 'xxl'].includes(windowState.value.breakpoint)
  )

  return {
    windowState,
    layoutConfig,
    isSmallScreen,
    isMediumScreen,
    isLargeScreen,
    
    // 布局控制
    toggleSidebar: () => globalWindowManager.toggleSidebar(),
    setSidebarWidth: (width: number) => globalWindowManager.setSidebarWidth(width),
    toggleRightPanel: () => globalWindowManager.toggleRightPanel(),
    setTaskPanelWidth: (width: number) => globalWindowManager.setTaskPanelWidth(width),
    toggleBottomPanel: () => globalWindowManager.toggleBottomPanel(),
    setBottomPanelHeight: (height: number) => globalWindowManager.setBottomPanelHeight(height),
    
    // 全屏控制
    toggleFullscreen: () => globalWindowManager.toggleFullscreen(),
    
    // 面板管理
    registerPanel: (panel: PanelConfig) => globalWindowManager.registerPanel(panel),
    unregisterPanel: (panelId: string) => globalWindowManager.unregisterPanel(panelId),
    showPanel: (panelId: string) => globalWindowManager.showPanel(panelId),
    hidePanel: (panelId: string) => globalWindowManager.hidePanel(panelId),
    togglePanel: (panelId: string) => globalWindowManager.togglePanel(panelId),
    
    // 布局预设
    applyLayout: (layoutName: Parameters<typeof globalWindowManager.applyLayout>[0]) => 
      globalWindowManager.applyLayout(layoutName),
    
    // 存储
    saveLayout: () => globalWindowManager.saveLayoutToStorage(),
    loadLayout: () => globalWindowManager.loadLayoutFromStorage()
  }
}

// 面板注册Hook
export const usePanel = (config: PanelConfig) => {
  const { registerPanel, unregisterPanel } = useWindowManager()

  onMounted(() => {
    registerPanel(config)
  })

  onUnmounted(() => {
    unregisterPanel(config.id)
  })

  return {
    config
  }
}

// 响应式布局Hook
export const useResponsiveLayout = () => {
  const { windowState, layoutConfig, isSmallScreen, isMediumScreen, isLargeScreen } = useWindowManager()

  const chatAreaStyle = computed(() => {
    const sidebar = layoutConfig.value.sidebarCollapsed ? 0 : layoutConfig.value.sidebarWidth
    const rightPanel = layoutConfig.value.rightPanelVisible ? layoutConfig.value.taskPanelWidth : 0
    
    return {
      marginLeft: `${sidebar}px`,
      marginRight: `${rightPanel}px`,
      width: `calc(100% - ${sidebar + rightPanel}px)`
    }
  })

  const sidebarStyle = computed(() => ({
    width: layoutConfig.value.sidebarCollapsed ? '0' : `${layoutConfig.value.sidebarWidth}px`,
    transform: layoutConfig.value.sidebarCollapsed ? 'translateX(-100%)' : 'translateX(0)'
  }))

  const rightPanelStyle = computed(() => ({
    width: `${layoutConfig.value.taskPanelWidth}px`,
    transform: layoutConfig.value.rightPanelVisible ? 'translateX(0)' : 'translateX(100%)'
  }))

  const bottomPanelStyle = computed(() => ({
    height: `${layoutConfig.value.bottomPanelHeight}px`,
    transform: layoutConfig.value.bottomPanelVisible ? 'translateY(0)' : 'translateY(100%)'
  }))

  return {
    windowState,
    layoutConfig,
    isSmallScreen,
    isMediumScreen,
    isLargeScreen,
    chatAreaStyle,
    sidebarStyle,
    rightPanelStyle,
    bottomPanelStyle
  }
}

// 初始化时加载布局
onMounted(() => {
  globalWindowManager.loadLayoutFromStorage()
})

// 页面卸载时保存布局
onUnmounted(() => {
  globalWindowManager.saveLayoutToStorage()
})

export default globalWindowManager